package org.example.filter;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.feign.AuthFeign;
import org.example.pojo.AuthInfo;
import org.example.pojo.Respond;
import org.example.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Component
@SuppressWarnings("ALL")
@Order(10151)
@Slf4j
public class AuthFilter implements GlobalFilter {

    @Resource
    @Lazy
    private AuthFeign authFeign;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        URI route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);

        if(request.getPath().value().equals("/auth/getToken")){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");

        log.info("Token: "+token+" path: "+route.toString());



        Respond<String> stringRespond = authFeign.hasAuth(request.getPath().value(), token);

        if(stringRespond.getStatusCode()==2||stringRespond.getStatusCode()==0){
            log.info(stringRespond.toString());
            return chain.filter(exchange);
        }

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type","application/json");

        DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONBytes(stringRespond));


        return response.writeWith(Flux.just(wrap));

    }

    private byte[] getSingleData(String info){
        return info.getBytes(StandardCharsets.UTF_8);
    }

}
